package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.*;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishMapper;
import com.sky.mapper.FlavorMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private FlavorMapper flavorMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Autowired
    private SetmealMapper setmealMapper;

    /**
     * 涉及到口味和菜品两次数据库操作，需要加事务操作的注解
     *
     * @param dish
     */
    @Override
    @Transactional
    public void save(DishDTO dish) {

        Dish newDish = new Dish();
        BeanUtils.copyProperties(dish, newDish);
        newDish.setStatus(StatusConstant.DISABLE);

        //将菜品数据插入对应表
        dishMapper.insert(newDish);

        Long id=newDish.getId();

        List<DishFlavor> flavors = dish.getFlavors();
        if (flavors != null && flavors.size() > 0) {
            for (DishFlavor flavor : flavors) {
                flavor.setDishId(id);
            }
            flavorMapper.insert(flavors);
        }

    }

    /**
     * 分页查询菜品信息
     * @param dishPageQueryDTO
     * @return
     */
    public PageResult page(DishPageQueryDTO dishPageQueryDTO){

        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());
        Page<DishVO> pageResult=dishMapper.pageQuery(dishPageQueryDTO);

        //包装一个page result的对象
        long total=pageResult.getTotal();
        List<DishVO> dishList=pageResult.getResult();

        return  new PageResult(total,dishList);
    }

    @Override
    @Transactional
    public void delete(List<Long> ids){

        //起售的菜品不得删除，根据status判断
        for(Long id:ids){
            Dish dish=dishMapper.selectByID(id);
            if(dish.getStatus()==StatusConstant.ENABLE){
                log.error("当前菜品正在销售，不得删除");
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }

        //当前菜品被套餐关联就不可以删除

        List<Long> dish=setmealDishMapper.selectByID(ids);
        if(dish!=null&&dish.size()>0){
            log.error("当前菜品被套餐关联，不得删除");
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }


        //删除所有选中的菜品数据
        dishMapper.deleteByID(ids);
        //删除时需要删除关联的口味
        flavorMapper.deleteByDishID(ids);


    }

    @Transactional
    @Override
    public DishVO getById(Long id){

        //两次查询，需要用事务注解保证查询成功
        Dish dish=dishMapper.selectByID(id);
        List<DishFlavor> flavorList= flavorMapper.selectByDishID(id);

        String categoryName=dishMapper.selectCategoryNameByID(id);

        DishVO dishVO=new DishVO();
        BeanUtils.copyProperties(dish,dishVO);

        dishVO.setFlavors(flavorList);
        dishVO.setCategoryName(categoryName);

        return dishVO;

    }

    @Override
    public void update(DishDTO dishDTO){

        Dish newDish = new Dish();
        BeanUtils.copyProperties(dishDTO, newDish);


        dishMapper.update(newDish);


        //打包成一个数组容器
        List<Long> dishIds=new ArrayList<>();
        dishIds.add(dishDTO.getId());
        flavorMapper.deleteByDishID(dishIds);

        List<DishFlavor> dish_flavors = dishDTO.getFlavors();
        if (dish_flavors != null && dish_flavors.size() > 0) {
            for (DishFlavor flavor : dish_flavors) {
                flavor.setDishId(dishDTO.getId());
            }
            flavorMapper.insert(dish_flavors);
        }



    }

    @Override
    public List<Dish> getByCategoryId(Long categoryId){

        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();

        return dishMapper.selectByCategoryId(dish);
    }

    @Override
    public void status(Integer status, Long id){

        Dish dish=Dish.builder().
                id(id).
                status(status).
//                updateTime(LocalDateTime.now()).
//                updateUser(BaseContext.getCurrentId()).
        build();
        dishMapper.update(dish);

        if (status == StatusConstant.DISABLE) {
            // 如果是停售操作，还需要将包含当前菜品的套餐也停售
            List<Long> dishIds = new ArrayList<>();
            dishIds.add(id);
            // select setmeal_id from setmeal_dish where dish_id in (?,?,?)
            List<Long> setmealIds = setmealDishMapper.selectByID(dishIds);
            if (setmealIds != null && setmealIds.size() > 0) {
                for (Long setmealId : setmealIds) {
                    Setmeal setmeal = Setmeal.builder()
                            .id(setmealId)
                            .status(StatusConstant.DISABLE)
                            .build();
                    setmealMapper.update(setmeal);
                }
            }
        }
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.selectByCategoryId(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = flavorMapper.selectByDishID(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }

}
